<template>
  <div
    v-loading.fullscreen="loading"
    class="home-page scrollbar"
  >
    <Header />
    <div class="main-content">
      <div class="unleash-container">
        <div class="page-title">Snapshot Your $JOKER</div>
        <div class="page-subtitle">Snapshot Deadline: Aug 10, 2025, 23:59 UTC</div>

        <div class="user-info user-info-mining">
          <h3 class="section-title">STEP 1: Sign in to Mining Account</h3>
          <div
            v-if="!userInfo || userInfo.account_type === 'x'"
            class="info-row"
          >
            <span class="info-label">X ACCOUNT</span>
            <div class="info-value-container">
              <span
                v-if="userInfo && userInfo.account_type === 'x'"
                class="info-value"
              >
                @{{ userInfo.username }}
              </span>
              <button
                v-if="userInfo"
                :disabled="userInfo.account_type !== 'x'"
                class="small-btn"
                @click="signOut"
              >LOG OUT</button>
              <button
                v-else
                class="small-btn"
                @click="onLoginByX"
              >SIGN IN</button>
            </div>
          </div>
          <div
            v-if="!userInfo || userInfo.account_type === 'google'"
            class="info-row"
          >
            <span class="info-label">GOOGLE ACCOUNT</span>
            <div class="info-value-container">
              <span
                v-if="userInfo && userInfo.account_type === 'google'"
                class="info-value"
              >
                @{{ userInfo.username }}
              </span>
              <button
                v-if="userInfo"
                :disabled="userInfo.account_type !== 'google'"
                class="small-btn"
                @click="signOut"
              >LOG OUT</button>
              <button
                v-else
                class="small-btn"
                @click="onLoginByGoogle"
              >SIGN IN</button>
            </div>
          </div>

          <div class="info-row">
            <span class="info-label">Mining Account Balance</span>
            <span
              v-if="userInfo"
              class="info-value token-amount"
            >{{ formatNum(userInfo?.joker_coin || 0) }}</span>
            <span v-else class="info-value token-amount">--</span>
          </div>

          <div class="snapshot-status-block">
            <div class="info-row">
              <span class="info-label">SNAPSHOT STATUS</span>
              <span v-if="!userInfo" class="info-value">--</span>
              <span v-else-if="!userInfo.wallet_address" class="info-value">Not Started</span>
              <span v-else class="info-value">Completed</span>
            </div>
            <!-- <div class="info-row">
              <span class="info-label">SNAPSHOT XPUB（RGB）</span>
              <span class="info-value">{{ shortAddress(userInfo?.rgb_pub || '--') }}</span>
            </div> -->
            <div class="info-row">
              <span class="info-label">SNAPSHOT WALLET ADDRESS</span>
              <span class="info-value">{{ shortAddress(userInfo?.btc_pub || '--') }}</span>
            </div>
            <!-- <div class="info-row">
              <span class="info-label">SNAPSHOT TOKEN AMOUNT</span>
              <span
                v-if="userInfo && userInfo.wallet_address"
                class="info-value"
              >{{ formatNum(userInfo?.joker_coin || 0) }}</span>
              <span v-else class="info-value">--</span>
            </div> -->
          </div>
        </div>

        <!-- 钱包连接区块 -->
        <div class="user-info user-info-wallet">
          <h3 class="section-title">STEP 2: Link Your RGB Wallet</h3>
          <p class="section-note">Once linked, the wallet cannot be changed</p>
          <div class="divider"></div>

          <div v-if="userInfo && userInfo.wallet_address" class="info-row">
            <div style="text-align: center; width: 100%;">
              <span class="info-label" style="font-size: 19px; color: #00FFFF; display: flex; align-items: center; justify-content: center; margin-bottom: 8px;">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right: 8px;">
                  <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="#00FFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                </svg>SNAPSHOT COMPLETED
              </span>
              <div style="font-size: 13px; color: rgba(0, 255, 255, 0.6); font-family: 'Share Tech Mono', monospace; letter-spacing: 0.5px;">Airdrop is coming. Check BlockJoker’s X account for updates.</div>
            </div>
          </div>
          <div v-else class="info-row">
            <span class="info-label">Connect Snapshot Wallet</span>
            <div class="info-value-container">
              <span class="info-value"></span>
              <button
                :class="{ 'btn-unavailable': !userInfo }"
                class="small-btn"
                @click="connectWallet"
              >Connect</button>
            </div>
          </div>
          <!-- <div class="info-row">
            <span
              class="info-label"
            >
              <img src="../../assets/images/joker.png" alt="Joker" class="joker-img"> MY $JOKER
            </span>
            <span class="info-value token-amount">0</span>
          </div> -->
        </div>

        <!-- <button class="connect-btn" disabled="" style="opacity: 0.5;">Unleash Your $JOKER</button>

        <p class="not-connected" style="color: rgb(255, 217, 102);">Sign in with your X or Google
          mining account first</p>

        <div class="unleash-info">
        </div>

        <div class="dashboard-container">
          <a href="https://blockjoker.org/lowairdrop" target="_blank" rel="noopener noreferrer"
            class="dashboard-link">Unleash Dashboard</a>
        </div> -->

        <!-- <div class="punchline-container">
          <p class="punchline-text">That's not the end. That's the punchline.</p>
        </div> -->

        <div class="airdrop-info">
        </div>
      </div>
    </div>
  </div>

  <div v-if="visibleConflictDialog" class="custom-popup">
    <div class="custom-popup-content">
      <div class="custom-popup-message">
        This wallet is already linked to another mining account.
      </div>
      <button class="custom-popup-close-btn" @click="visibleConflictDialog=false">OK</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onBeforeUnmount, inject, computed } from 'vue'
import { ElMessage } from 'element-plus'
import BitlightWalletSdk from '@bitlight/wallet-sdk'
import { useRoute } from 'vue-router'
// import sysend from 'sysend'
import { useAccountStore } from '../../stores/account.js'
import { useCommonStore } from '../../stores/index'
import Header from '../../components/HeaderNew.vue'
import { log } from '../../utils/log.js'
import { googleClientId } from '../../const/index'
import db from '../../utils/localstorage.js'
import { formatNum } from '../../utils/index.js'

const $request = inject('$request')
const route = useRoute()

const $axios = inject('$axios')
const accountStore = useAccountStore()
const commonStore = useCommonStore()
const loading = ref(false)
const visibleConflictDialog = ref(false)

const env = import.meta.env

let bitlightWalletSdk = new BitlightWalletSdk()
const connectWallet = async () => {
  loading.value = true
  try {
    const isReady = bitlightWalletSdk.isReady()
    if (!isReady) {
      throw new Error('Bitlight wallet not injected yet.')
    }
    await bitlightWalletSdk.connect()
    const network = await bitlightWalletSdk.getNetwork()
    if (network !== 'bitcoin') {
      await bitlightWalletSdk.switchNetwork('bitcoin')
    }
    const accounts = await bitlightWalletSdk.getAccounts()
    await saveWalletInfo(
      accounts.rgb_pub,
      accounts.btc_pub,
      accounts.address
    )
  } catch (error) {
    log(error)
    if (error?.response?.data?.detail === 'Wallet address conflict') {
      // 钱包账户已经被快照
      visibleConflictDialog.value = true
    } else if (error === 'No account selected.') {
      // 钱包未登录
      ElMessage({
        message: 'Please create or import a wallet account to continue.',
        type: 'error'
      })
    } else if (error.message === 'Bitlight wallet not injected yet.') {
      // 未安装钱包插件
      ElMessage({
        message: 'Please install the Bitlight wallet.',
        type: 'error'
      })
      setTimeout(() => {
        window.open('https://chromewebstore.google.com/detail/bitlight-wallet/fdojfgffiecmmppcjnahfgiignlnehap')
      }, 800)
    } else {
      ElMessage({
        message: error.message || error,
        type: 'error'
      })
    }
  }
  if (!userInfo.value) {
    return
  }
  loading.value = false
}

function shortAddress(addr) {
  if (addr) {
    if (addr.length > 10) {
      return `${addr.substring(0, 6)}...${addr.substring(addr.length - 4, addr.length)}`
    } else {
      return `${addr}`
    }
  } else {
    return ''
  }
}

const saveWalletInfo = async (rgb_pub, btc_pub, wallet_address) => {
  const { data } = await $request.post('/profile', {
    rgb_pub,
    btc_pub,
    wallet_address
  })
  if (!data.ok) {
    throw new Error(data.detail)
  }
  await accountStore.getUser()
}

const disconnect = () => {
  bitlightWalletSdk.disconnect()
}


const userInfo = computed(() => {
  return accountStore.user
})

const signOut = () => {
  db.remove('ACCESS_TOKEN')
  db.remove('USER')
  location.reload(true)
}

const onLoginByGoogle = () => {
  loading.value = true
  const state = Math.random().toString(36).substring(2)
  const nonce = Math.random().toString(36).substring(2)

  db.save('google_nonce', nonce)
  let redirectUri = `${window.location.origin}/google-callback`
  // let redirectUri = `https://blockjoker.org/google-callback`
  if (env.VITE_ENV_NAME === 'development') {
    redirectUri = `https://previewdev.blockjoker.org/google-callback`
  }

  const scope = 'email profile'
  const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth')
  authUrl.searchParams.append('client_id', googleClientId)
  authUrl.searchParams.append('nonce', nonce)
  authUrl.searchParams.append('response_type', 'id_token')
  authUrl.searchParams.append('scope', scope)
  // authUrl.searchParams.append('access_type', 'offline')
  authUrl.searchParams.append('redirect_uri', redirectUri)
  authUrl.searchParams.append('state', state)
  authUrl.searchParams.append('prompt', 'select_account')

  sessionStorage.setItem('googleOAuthState', state)
  location.href = authUrl.toString()
}

const onLoginByX = async () => {
  loading.value = true
  try {
    const { data } = await $request.login(`/authorization/url?invite=${route.query.invite_code || ''}`)
    if (!data.ok) {
      throw new Error('Login failed')
    }
    window.location.href = data.result
  } catch (error) {
    log(error)
    loading.value = false
  }
}

onBeforeMount(async () => {
  if (!accountStore.user) {
    accountStore.getUser()
  }
  const isConnected = bitlightWalletSdk.isConnected()
  if (userInfo.value && isConnected) {
    disconnect()
  }
})

onBeforeUnmount(() => {
})
</script>

<style lang="less" scoped>
.home-page {
  flex: 1;
  height: 100%;
  overflow: auto;
}

.scrollbar {
  /* 可根据需要添加滚动条样式 */
}

.main-content {
  opacity: 1 !important;
  transition: opacity 0.8s ease;
  padding: 0;
  width: 100%;
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.unleash-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  max-width: 760px;
  margin: 0 auto;
  padding: 32px;
  position: relative;
}

.page-title {
  color: #00FFFF;
  font-size: 22px;
  font-weight: 500;
  text-align: center;
  margin-bottom: 10px;
  font-family: 'Orbitron', sans-serif;
  text-transform: uppercase;
  letter-spacing: 2px;
  text-shadow: 0 0 15px rgba(0, 255, 255, 0.4);
  position: relative;
  width: 100%;
}

.page-title:after {
  display: none;
  content: "";
  position: absolute;
  bottom: -15px;
  left: 50%;
  transform: translateX(-50%);
  width: 300px;
  height: 1px;
  background: linear-gradient(90deg, transparent, #00A3A3, transparent);
}

.page-subtitle {
  color: rgba(0, 255, 255, 0.7);
  font-size: 14px;
  text-align: center;
  margin-bottom: 30px;
  font-family: 'Share Tech Mono', monospace;
  letter-spacing: 1px;
  font-weight: 400;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(0, 255, 255, 0.2);
  padding: 40px;
  border-radius: 0px;
  width: 100%;
  margin-bottom: 40px;
  position: relative;
  overflow: hidden;
  min-width: 500px;
}


.section-title {
  width: 100%;
  text-transform: uppercase;
  letter-spacing: 2px;
  text-align: center;
  position: relative;
  display: inline-block;
  padding: 0 30px;
  margin-left: auto;
  margin-right: auto;
  color: #00FFFF;
  font-family: 'Orbitron', sans-serif;
  font-size: 14px;
  margin-top: 0px;
  margin-bottom: 25px;
}

.section-title::before,
.section-title::after {
  content: "//";
  position: absolute;
  color: rgba(0, 255, 255, 0.6);
}

.section-title::before {
  left: 0;
}

.section-title::after {
  right: 0;
}

/* 为"Sign in to Mining Account"标题设置特定样式 */
.user-info-mining > .section-title:first-child {
  margin-top: 0;
  margin-bottom: 25px;
}

/* 为"Link Your RGB Wallet"标题设置特定样式 */
.user-info-wallet > .section-title:first-child {
  margin-top: 0;
  margin-bottom: 0px;
} 

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.15);
  line-height: 23px;
}

.info-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.info-label {
  font-family: 'Share Tech Mono', monospace;
  color: rgba(0, 255, 255, 0.7);
  font-size: 13px;
  letter-spacing: 1px;
  text-transform: uppercase;
}

.info-value-container {
  display: flex;
  align-items: center;
}

.info-value {
  font-family: 'Share Tech Mono', monospace;
  color: #00FFFF;
  font-size: 13px;
  letter-spacing: 1px;
}


.token-amount {
  font-size: 16px;
  color: #00FFFF;
  font-weight: 400;
  text-shadow: none;
  letter-spacing: 1px;
  font-family: 'Share Tech Mono', monospace;
}


.snapshot-status-block {
  background: rgba(0,255,255,0.04);
  border: 1px dashed rgba(0,255,255,0.15);
  border-radius: 4px;
  margin-top: 0px;
  padding: 10px 12px 6px 12px;
  font-size: 15px;
  color: #5BAAAA;
  width: 100%;
  max-width: none;
  box-sizing: border-box;
}
.snapshot-status-block .info-row {
  min-height: 20px;
  margin-bottom: 2px;
  padding-bottom: 0;
  border-bottom: none;
}
.snapshot-status-block .info-label,
.snapshot-status-block .info-value {
  font-size: 13px;
  color: #00FFFF;
  font-weight: 400;
}

.divider {
  width: 100%;
  height: 1px;
  background: linear-gradient(90deg, transparent, #00A3A3, transparent);
  margin: 0 auto 16px;
}

.section-note {
  color: #FFD966;
  font-size: 13px;
  margin-top: 0;
  margin-bottom: 10px;
  font-style: italic;
  text-align: center;
}

.connect-btn {
  font-family: 'Share Tech Mono', monospace;
  background-color: transparent;
  color: #00FFFF;
  border: 1px solid #00FFFF;
  padding: 16px 40px;
  font-size: 17.6px;
  text-transform: uppercase;
  cursor: pointer;
  transition: all 0.3s ease;
  letter-spacing: 3px;
  margin-bottom: 32px;
  width: 100%;
  position: relative;
  overflow: hidden;
  font-weight: 600;
}

.connect-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(0, 255, 255, 0.2), transparent);
  transition: all 0.6s ease;
}

.connect-btn:hover {
  background-color: rgba(0, 255, 255, 0.1);
  color: #00FFFF;
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.3);
  transform: translateY(-2px);
}

.connect-btn:hover::before {
  left: 100%;
}

.small-btn {
  font-family: 'Share Tech Mono', monospace;
  background-color: transparent;
  color: #00FFFF;
  border: 1px solid #00FFFF;
  padding: 6.4px 16px;
  font-size: 12.8px;
  text-transform: uppercase;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: 15px;
  width: auto;
  min-width: 120px;
  text-align: center;
  white-space: nowrap;
  letter-spacing: 1px;

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.small-btn:hover {
  background-color: rgba(0, 255, 255, 0.1);
  color: #00FFFF;
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
}

.btn-unavailable {
  opacity: 0.5;
  cursor: not-allowed;
}

.not-connected {
  color: rgb(255, 217, 102);
  margin-bottom: 104px;
  font-weight: normal;
  text-align: center;
  letter-spacing: 0.5px;
  text-shadow: 0 0 10px rgba(255, 217, 102, 0.3);
  font-family: 'IBM Plex Mono', monospace;
  font-size: 14.4px;
}

.unleash-info {
  text-align: center;
  margin-bottom: 32px;
  position: relative;
  padding: 32px;
  width: 100%;
  max-width: 750px;
}

.dashboard-link {
  font-family: 'Share Tech Mono', monospace;
  font-size: 13.6px;
  color: #0DA7A7;
  text-decoration: underline;
  transition: color 0.3s ease;
  display: inline-block;
  margin-top: 0px;
  margin-bottom: 0;
  position: relative;
}

.dashboard-link:hover {
  color: #00FFFF;
}

.dashboard-container {
  text-align: center;
  margin-top: -100px;
  position: relative;
  z-index: 5;
}

.punchline-container {
  position: relative;
  width: 100%;
  text-align: center;
  padding: 10px 0;
}

.punchline-text {
  font-family: 'Share Tech Mono', monospace;
  font-size: 13.6px;
  color: #5BAAAA;
  letter-spacing: 0.5px;
  opacity: 0.8;
  margin: 0;
  padding: 0;
  font-weight: 400;
}

.joker-img {
  height: 1em;
  width: auto;
  vertical-align: middle;
  display: inline-block;
  margin-bottom: 0.2em;
}

.airdrop-info {
  text-align: center;
  margin-bottom: 32px;
  position: relative;
  padding: 32px;
  width: 100%;
  max-width: 750px;
}

.custom-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
}

.custom-popup-content {
    background-color: #000000;
    border: 1px solid #00FFFF;
    padding: 30px;
    max-width: 600px;
    width: 90%;
    text-align: center;
    color: #00FFFF;
    font-family: 'Share Tech Mono', monospace;
    box-shadow: 0 0 20px rgba(0, 255, 255, 0.3);
}

.custom-popup-message {
    margin-bottom: 20px;
    font-size: 1rem;
    line-height: 1.5;
}

.custom-popup-close-btn {
    background-color: transparent;
    border: 1px solid #00FFFF;
    color: #00FFFF;
    padding: 8px 20px;
    font-size: 0.9rem;
    cursor: pointer;
    font-family: 'Share Tech Mono', monospace;
    transition: all 0.3s ease;
}

.custom-popup-close-btn:hover {
    background-color: rgba(0, 255, 255, 0.1);
} 
</style>
